package py.edu.ucom.cadira.xml;

import org.jdom.Document;
import org.jdom.Element;

import py.edu.ucom.cadira.net.XMLSerializable;

public class XMLSerializer {

	public static final String GLOBAL_HEADER="CADIRA";
	public static final String ATT_TYPE="type";
	
	public static XMLSerializable fromXML(Document doc) throws BadProtocolException {
		Element root=doc.getRootElement();
		if (root.getName().equals(GLOBAL_HEADER)) {
			String type = root.getAttributeValue(ATT_TYPE);
			try {
				Class classType = Class.forName(type);
				Object o=classType.newInstance();
				if(o instanceof XMLSerializable){
					XMLSerializable xmlSerializable=(XMLSerializable)o;
					 xmlSerializable.fromXML(doc);
					 return xmlSerializable;
				}
			} catch (ClassNotFoundException e) {
				throw new BadProtocolException("Unsupported type "+type,e);
			} catch (InstantiationException e) {
				throw new BadProtocolException("Unsupported type "+type,e);
			} catch (IllegalAccessException e) {
				throw new BadProtocolException("Unsupported type "+type,e);
			}
			
		}else{
			throw new BadProtocolException("Unsupported package "+root.getName());
		}
		return null;
	}

	public static Document toXML(XMLSerializable serializable) {
		Document doc = new Document();
		Element root = new Element(XMLSerializer.GLOBAL_HEADER);
		root.setAttribute(XMLSerializer.ATT_TYPE, serializable.getClass().getName());
		doc.setRootElement(root);
		serializable.toXML(root);
		return doc;
		
	}
}
